//
//  AppDelegate.m
//  beautyLamp
//
//  Created by Tam Kwok To Michael on 2017/8/8.
//  Copyright © 2017年 Tam Kwok To Michael. All rights reserved.
//

#import "AppDelegate.h"
#import "BLHeader.h"
#import "GuideViewController.h"
#import "LoginViewController.h"
#import "BLNavigationController.h"
#import "LoginNet.h"
#import <MBProgressHUD.h>
#import "HomeViewController.h"
#import "CustomerOrderDetailViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import "PayViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self enterWitchController];
    [self.window makeKeyAndVisible];
    [WXApi registerApp:WX_APP_ID];
    [WeiboSDK enableDebugMode:YES];
    [WeiboSDK registerApp:WB_APP_KEY];
    //Required
    //notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:JPUSH_APP_KEY
                          channel:JPUSH_CHANNEL
                 apsForProduction:NO
            advertisingIdentifier:nil];
    
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
       // NSLog(@"resCode : %d,registrationID: %@",resCode,registrationID);
        NSString *userTel = [[NSUserDefaults standardUserDefaults] objectForKey:USERTEL];
        [JPUSHService setAlias:userTel completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        } seq: 0];
    }];

    return YES;
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}


- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    [self dealWithNotificationInfo:userInfo];
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    NSString *orderCode = [userInfo objectForKey:@"orderCode"];
    [self dealWithNotificationInfo:userInfo];
    completionHandler();  // 系统要求执行这个方法
    if (!orderCode) {
        return;
    }
    // 应用在前台 或者后台开启状态下，不跳转页面，让用户选择。
    UIApplication *application = [UIApplication sharedApplication];
    if (application.applicationState == UIApplicationStateActive || application.applicationState == UIApplicationStateBackground) {
        NSLog(@"acitve or background");
        CustomerOrderDetailViewController *VC = [[CustomerOrderDetailViewController alloc] init];
        VC.orderCode = orderCode;
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        UIViewController *controller = window.rootViewController;
        UINavigationController *navigation = (UINavigationController *)controller;
        [navigation pushViewController:VC animated:YES];
    }else{
        //杀死状态下，直接跳转到跳转页面。
        CustomerOrderDetailViewController *VC = [[CustomerOrderDetailViewController alloc] init];
        VC.orderCode = orderCode;
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        UIViewController *controller = window.rootViewController;
        UINavigationController *navigation = (UINavigationController *)controller;
        [navigation pushViewController:VC animated:YES];
    }
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [self dealWithNotificationInfo:userInfo];
    [JPUSHService handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
    [self dealWithNotificationInfo:userInfo];
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler {
    completionHandler(UIBackgroundFetchResultNewData);
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    [self dealWithNotificationInfo:userInfo];
}

#pragma mark 处理通知信息 将订单ID存入plist文件中
- (void)dealWithNotificationInfo:(NSDictionary *)userInfo {
    NSString *orderCode = [userInfo objectForKey:@"orderCode"];
    NSMutableDictionary *dic =[NSMutableDictionary dictionaryWithDictionary:[[NSUserDefaults standardUserDefaults] objectForKey:@"userDic"]];
    if (!dic) {
        dic = [[NSMutableDictionary alloc] init];
    }
    [dic setObject:orderCode forKey:orderCode];
    [[NSUserDefaults standardUserDefaults] setObject:dic forKey:@"userDic"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

# pragma mark 判断进入哪个界面
- (void)enterWitchController {
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *isLogin = [user objectForKey:Logined];
    // 表示用户登成功， 进入主页面
    if(isLogin && [isLogin isEqualToString:Logined]) {
        self.window.rootViewController = [[BLNavigationController alloc] initWithRootViewController:[[HomeViewController alloc] init]];
    } else { // 不存在则用户先登录
        self.window.rootViewController = [[BLNavigationController alloc] initWithRootViewController:[[LoginViewController alloc] init]];
    }
}

// 9.0以后
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    NSString *urlStr = [url absoluteString];
    if ([urlStr hasPrefix:WX_PREFIX] || [urlStr hasPrefix:WX_PAY_PREFIX]) {
        return [WXApi handleOpenURL:url delegate:self];
    }else if ([urlStr hasPrefix:QQ_PREFIX]){
        [TencentApiInterface handleOpenURL:url delegate:self];
        return [TencentOAuth HandleOpenURL:url];
    }else if ([urlStr hasPrefix:WB_PRIFIX]) {
        return [WeiboSDK handleOpenURL:url delegate:self];
    }else  if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"AlipaySDK  result = %@",resultDic);
        }];
    }
    if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回authCode
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
            //【由于在跳转支付宝客户端支付的过程中，商户app在后台很可能被系统kill了，所以pay接口的callback就会失效，请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】
            NSLog(@"platformapi  result = %@",resultDic);
        }
         ];
    }
    return YES;
}

//9.0之前
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"AlipaySDK  result =  %@",resultDic);
        }];
    }
    return YES;
}

-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    NSString *urlStr = [url absoluteString];
    if ([urlStr hasPrefix:WX_PREFIX]) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}

#pragma mark 微博授权后的回调
- (void)didReceiveWeiboResponse:(WBBaseResponse *)response {
    if ([response isKindOfClass:WBAuthorizeResponse.class]) {
        WBAuthorizeResponse *resp = (WBAuthorizeResponse *)response;
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.window animated:YES];
        if (!resp.userID || !resp.accessToken) {
            hud.mode = MBProgressHUDModeText;
            hud.label.text = @"授权失败！";
            [hud hideAnimated:YES afterDelay:2];
            return;
        }
        hud.mode = MBProgressHUDModeIndeterminate;
        [LoginNet WEIBOLoginToken:resp.accessToken openID:resp.userID completer:^(id resultObject, NSError *error) {
            if (error) {
                hud.mode = MBProgressHUDModeText;
                hud.label.text = [error localizedDescription];
                [hud hideAnimated:YES afterDelay:2];
                return ;
            }
            [hud hideAnimated:YES];
            [[NSUserDefaults standardUserDefaults] setObject:Logined forKey:Logined];
            self.window.rootViewController = [[BLNavigationController alloc] initWithRootViewController:[[HomeViewController alloc] init]];
        }];
    }
}

- (void)didReceiveWeiboRequest:(WBBaseRequest *)request {
}

- (BOOL)onTencentResp:(TencentApiResp *)resp {
    return YES;
}

#pragma mark - 微信授权响应接口
- (void)onResp:(BaseResp*)resp {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.window animated:YES];
    // 微信授权
    if([resp isKindOfClass:[SendAuthResp class]]){
        SendAuthResp *res = (SendAuthResp *)resp ;
        // 用户登录
        __weak typeof (self)weakself = self;
        if(res.code && ![@"" isEqualToString:res.code]){
            __strong typeof (weakself)self =weakself;
             hud.mode = MBProgressHUDModeIndeterminate;
            [LoginNet weChatLoginGetToken:res.code completer:^(id result, NSError *error) {
                if(result) {
                    [hud hideAnimated:YES];
                    [[NSUserDefaults standardUserDefaults] setObject:Logined forKey:Logined];
                    self.window.rootViewController = [[BLNavigationController alloc] initWithRootViewController:[[HomeViewController alloc] init]];
                }else {
                    hud.label.text = @"登录失败！";
                    hud.mode = MBProgressHUDModeText;
                    [hud hideAnimated:YES afterDelay:2];
                }
            }];
       }
    }else if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
    }else if ([resp isKindOfClass:[PayResp class]]) {
        NSLog(@"wechat pay result");
        //启动微信支付的response
        NSString *payResoult = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
        //支付返回结果，实际支付结果需要去微信服务器端查询
        hud.mode = MBProgressHUDModeText;
         UINavigationController *navi = (UINavigationController *)self.window.rootViewController;
         NSMutableArray *childControllers = [NSMutableArray arrayWithArray:navi.childViewControllers];
        switch (resp.errCode) {
            case 0:
            case -1:
                [hud hideAnimated:YES];
                NSLog(@"llh wechat pay");
                if ([childControllers.lastObject class] == [PayViewController class]) {
                    [childControllers removeLastObject];
                    [navi setViewControllers:childControllers];
                    NSLog(@"llh wechat payviewcontroller kill");
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"payNotification" object:nil];
                }
                break;
            case -2:
                payResoult = @"用户已经退出支付！";
                break;
            default:
                payResoult = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                break;
        }
        hud.label.text = payResoult ;
        [hud hideAnimated:YES afterDelay:3];
    }
}

- (void)onReq:(BaseReq *)req {
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
